package za.org.jcicada.comms.impl;

import java.io.IOException;
import java.nio.ByteBuffer;

import za.org.jcicada.comms.ICommsBuffer;
import za.org.jcicada.comms.impl.tcp.TcpSelector.ICallback;
import za.org.jcicada.comms.messages.CommsMessage;

public abstract class SelectableConnection extends ConnectionBase implements ICallback {

	/** Buffer for holding received but unprocessed data. */
	protected ICommsBuffer commsBuffer;
	
	/**
	 * Feed a buffer of read data from the selector loop into the CommsBuffer.
	 * 
	 * @param buffer
	 *            of values read from the channel
	 * @throws Exception
	 */
	public void feedBuffer(ByteBuffer buffer) throws IOException {
		commsBuffer.feedByteBuffer(buffer);

		// pass all waiting messages on the message listener
		CommsMessage msg;
		while ((msg = commsBuffer.popMessage()) != null) {
			MessageExecutor.getInstance().submit(getListener(), msg);
		}
	}

}
